package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
   @Autowired
    private ItemMapper itemMapper;
   @Autowired
   private ItemDescMapper itemDescMapper;

    /**
     * PageResult{pageNum,pageSize,rows分页数据,total总数}
     * 业务数据的VO对象
     * page:MP中的分页对象 官方API
     *
     */
    @Override
    public PageResult findItemByPage(PageResult pageResult) {
        IPage<Item> page =new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper();
       boolean flag= StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"title",pageResult.getQuery());
        //经过程序的分页，其中的数据全部获取
       page= itemMapper.selectPage(page,queryWrapper);
       long total = page.getTotal();
       List<Item> itemList = page.getRecords();//MP获取分页后的结果
        return pageResult.setTotal(total).setRows(itemList);
    }

    @Override
    @Transactional
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }
/**
 * 完成两张表的入库操作
 * 1.item表
 * 2.item_desc表，要求id一致
 */


    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
       Item item= itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);//入库之后才有主键id
        //MP已经实现了主键的自动回显，所以id有值
        //商品详情表
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);


    }

    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }
}
